package com.ruoyi.service.jpjs.costcode.impl;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mapper.SysParameterMapper;
import com.ruoyi.mapper.jpjs.costcode.CostCodeMapper;
import com.ruoyi.service.jpjs.costcode.CostCodeService;
import com.ruoyi.util.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

@Service
public class CostCodeServiceImpl implements CostCodeService {

    @Autowired
    private CostCodeMapper costCodeMapper;

    @Autowired
    private SysParameterMapper sysParameterMapper;

    @Override
    public List<Map<String, Object>> findCostCodeAll(Map<String, Object> map) {
        return costCodeMapper.findCostCodeAll(map);
    }

    @Override
    public Map<String, Object> findCostCode(String codeId) {
        return costCodeMapper.findCostCode(codeId);
    }

    @Override
    public int findChildLevel(String codeId) {
        return costCodeMapper.findChildLevel(codeId);
    }

    @Override
    @Transactional
    public int saveCostCode(Map<String, Object> map) {
        int num = 0;
        if (!map.containsKey("codeId")) {
            String ancestors = costCodeMapper.findAncestors((String) map.get("parentId"));
            map.put("ancestors", ancestors == null ? 0 : ancestors);
            num = costCodeMapper.addCostCode(map);
        } else {
            num = costCodeMapper.editCostCode(map);
        }
        return num;
    }

    @Override
    public int deleteCostCode(String codeId) {
        return costCodeMapper.deleteCostCode(codeId);
    }

    @Override
    public int checkCodeNumUnique(Map<String, Object> map) {
        return costCodeMapper.checkCodeNumUnique(map);
    }

    @Override
    @Transactional
    public int importData(MultipartFile file) {
        List<Map<String, Object>> list = ExcelUtils.getExcelData(file, new String[]{"codeNum", "codeName", "codeFeature", "codeUnit"});
        for (Map<String, Object> map : list) {
            String codeUnit = sysParameterMapper.findIdByName(map.get("codeUnit") != null ? map.get("codeUnit").toString() : "", "成本科目编码单位");
            map.put("codeUnit", StringUtils.isNotEmpty(codeUnit) ? codeUnit : "");
        }
        return costCodeMapper.addCostCodeList(list);
    }
}
